import React, { Component } from "react";

export default class App extends Component {
  state = {
    list: [{ id: 1, name: "87", isChecked: false }],
    myRef: React.createRef(),
  };
  render() {
    let newList = this.state.list.map((item, index) => (
      <li key={item.id}>
        <input
          type="checkbox"
          checked={item.isChecked}
          onChange={() => this.changeCheck(index)}
        />
        {item.name}
        <button onClick={() => this.delClick(item)}>删除</button>
      </li>
    ));
    return (
      <section>
        <div>
          <input type="text" ref={this.state.myRef} />
          <button onClick={() => this.handleClick()}>添加</button>
          <button onClick={this.clickAll.bind(this)}>全选</button>
        </div>
        <ul>{newList}</ul>
      </section>
    );
  }
  handleClick = () => {
    let arrList = [...this.state.list];
    arrList.push({
      id: Math.random() * 1,
      name: this.state.myRef.current.value,
      isChecked: false,
    });
    this.state.myRef.current.value = "";
    this.setState({ list: arrList });
  };
  delClick = (v) => {
    console.log(v);
    let concatList = [...this.state.list];
    this.setState({
      list: concatList.filter((item) => item.id != v.id),
    });
  };
  changeCheck(index) {
    let newList = [...this.state.list];
    newList[index].isChecked = !newList[index].isChecked;
    this.setState({
      list: newList,
    });
  }
  clickAll() {
    console.log(this.state.list);
  }
}
